<template>
  <div class="details">
    <div v-for="item of ResolvedDatas" @dblclick="onCopyValue(item)" :style="{ 'flex': item.tag == 'attachment' || item.tag == 'localAttachment' ? '0 0 100%' : '' }">
      <label>{{ item.name }}</label>
      <template v-if="item.tag == 'view'">
        <a v-if="(item.value || '').indexOf('http') != -1" :href="item.value" target="_blank">访问</a>
        <span v-else v-html="item.value"></span>
      </template>
      <template v-else-if="item.tag == 'attachment'">
        <ul>
          <li v-for="path of getAttachments(item.value)">
            <a target="_blank" :href="path.path">{{ path.name }}</a>
          </li>
        </ul>
      </template>
      <template v-else-if="item.tag == 'localAttachment'">
        <ul>
          <li v-for="path of getLocalAttachments(item.value)">
            <a target="_blank" :href="hostUrl + path.path">{{ path.name }}</a>
          </li>
        </ul>
      </template>
      <template v-else-if="item.tag == 'request'">
        <Button type="primary" @click="getDoa" shape="round" size="small"><AppstoreAddOutlined /> 获取</Button>
      </template>
      <span v-else-if="item.tag == 'status'">{{ getWorkflowText(item.value) }}</span>
      <span v-else>{{ item.value }}</span>
    </div>
  </div>
  <Modal v-model:visible="showDoa" :centered="true" :width="1024" title="Doa详情" :footer="null" wrap-class-name="compact-modal">
    <Table bordered size="small" :columns="doaColumns" :pagination="false" :data-source="doaDetails.data">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key == 'custom'">
          <ul>
            <li v-for="d of record.DOARolesInColumnList">
              {{ `${d.RoleTypeName}(${d.OperationDesc})` }}
              <ul>
                <li v-for="c of d.SystemUserList">
                  {{ c.OperatorUserAccount && c.OperatorUserAccount != c.UserAccount ? `${c.OperatorUserID} - ${c.OperatorUserDisplayNameCN}(${c.OperatorUserDisplayNameEN})` : `${c.UserID} - ${c.UserDisplayNameCN}(${c.UserDisplayNameEN})` }}
                </li>
              </ul>
            </li>
          </ul>
        </template>
      </template>
    </Table>
    <div slot="footer"></div>
  </Modal>
</template>
<script setup>
  import { ref, reactive, watch, computed, inject, onMounted } from 'vue';

  import { getWorkflowText, fillDatas, resolveParams } from '@/libs/helpers.js';
  import { Button, Table, Modal } from 'ant-design-vue';
  import { AppstoreAddOutlined } from '@ant-design/icons-vue';

  const $http = inject('$http');
  const $message = inject('$message');
  const $copyText = inject('$copyText');

  const props = defineProps({
    data: {
      type: Object,
      defualt: function () {
        return {};
      }
    },
    env: {
      type: String,
      defualt: 'uat'
    }
  });

  const hosts = ref([]);
  const ResolvedDatas = ref([]);
  const showDoa = ref(false);
  const doaDetails = reactive({});

  const doaColumns = [
    { title: 'NodeId', dataIndex: 'NodeID', width: 100 },
    { title: 'DOA项ID', dataIndex: 'DOAItemID', width: 100 },
    { title: 'DOA角色', dataIndex: 'DOAColumnName', width: 120 },
    { title: 'Action', dataIndex: 'Action', width: 90 },
    { title: '审批列表', key: 'custom' }
  ];

  const hostUrl = computed(() => (hosts.value.find(h => h.env == props.env) || {}).url);

  watch(
    () => props.data,
    () => resolvedData()
  );

  function resolvedData() {
    if (!props.data) {
      return [];
    }

    let data = props.data;

    let rs = [
      { name: 'ID', value: data.ID },
      { name: '流水号', value: data.SerialNumber },
      { name: '标题', value: data.Title },
      { name: '流程编号', value: data.ProcessID },
      { name: '流程名称', value: data.ProcessName },
      { name: '流程组', value: `${data.ProcessGroupName}(${data.ProcessGroupID})`, copy: data.ProcessGroupID },
      { name: '项目', value: `${data.ProjectName}(${data.ProjectID})`, copy: data.ProjectID },
      { name: '部门', value: `${data.DepartmentName}(${data.DepartmentID})`, copy: data.DepartmentID },
      { name: '申请人', value: `${data.ApplicantUserDisplayNameCN}(${data.ApplicantUserID})`, copy: data.ApplicantUserID },
      { name: '流程开始时间', value: data.ProcStartDate },
      { name: '流程实例编号', value: data.ProcessInstanceID },
      { name: '最后审批人', value: `${data.LastApprovedUserDisplayNameCN}(${data.LastApprovedUserID})`, copy: data.LastApprovedUserID },
      { name: '最后审批时间', value: data.LastApprovedDate },
      { name: '流程状态', value: data.ProcessStatus, tag: 'status' },
      { name: 'DOA获取条件', value: data.DOAConditions, tag: 'request' },
      { name: '表单Url', value: data.BizFormUrl, tag: 'view' },
      { name: '暂缓', value: `${data.HoldStartDate || ''}\n${data.HoldComments || ''}` },
      { name: '附件(三方)', value: data.AttachmentUrls, tag: 'attachment' },
      { name: '附件(nwf)', value: data.LocalAttachmentUrls, tag: 'localAttachment' }
    ];

    ResolvedDatas.value = rs;
  }

  function getDoa() {
    let conditions = encodeURI(props.data.DOAConditions);

    if (conditions.toLowerCase().indexOf('processid') == -1) {
      conditions += `&ProcessID=${props.data.ProcessID}`;
    }

    $http.post(`/api/iworkflow/prod/workflow/doa`, { conditions: conditions }).then(res => {
      fillDatas(doaDetails, res);

      showDoa.value = true;
    });
  }

  function getHosts() {
    $http.get('/api/iworkflow/webapi/hosts').then(res => {
      hosts.value = (res || []).map(h => {
        return { env: h.env, url: h.url };
      });
    });
  }

  function getAttachments(attachement) {
    if (!attachement) {
      return [];
    }

    let rs = [];
    let items = attachement.split('|');

    for (let item of items) {
      let params = resolveParams(item);

      rs.push({
        name: params.get('filename') || '附件',
        path: item
      });
    }

    return rs;
  }

  function getLocalAttachments(attachement) {
    if (!attachement) {
      return [];
    }

    let rs = [];
    let items = attachement.split('|');

    for (let item of items) {
      let segments = item.split('\\');
      let fileName = segments[segments.length - 1];
      let params = fileName.split('_');

      rs.push({
        name: params[0].trim() + fileName.substr(fileName.indexOf('.')),
        path: item
      });
    }

    return rs;
  }

  function onCopyValue(item) {
    $copyText((item.copy || item.value) + '').then(() => {
      $message.success('结果已复制！');
    });
  }

  onMounted(() => {
    getHosts();
    resolvedData();
  });
</script>
<style lang="less">
  .details {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    background: #fff;
    column-count: 3;
    column-fill: balance;
    justify-content: space-between;

    &.block {
      padding: 0;
      margin: 0;

      > div {
        width: 100%;
        flex: 0 0 100%;
        display: flex;
        padding: 5px 0;
        align-items: center;
        border-bottom: 1px dashed #cccccc;

        &:last-of-type {
          border-bottom: none;
        }

        > label {
          width: 80px;
          text-align: right;
        }

        > span {
          flex: 1;
          word-wrap: none;
          cursor: pointer;
          overflow: auto;
          white-space: normal;
          max-height: 120px;
        }
      }
    }

    > div {
      flex: 0 0 33.3333%;
      padding: 6px 0 0 0;
      cursor: default;
      user-select: none;
      white-space: nowrap;

      > label {
        font-weight: bold;
        line-height: 1;
        &:after {
          content: '：';
        }
      }

      > span {
        word-wrap: none;
        cursor: pointer;
      }

      > ul {
        list-style: none;
        padding: 0;
        margin: 0;
        display: inline-block;
        counter-reset: number 0;
        white-space: normal;

        > li {
          position: relative;
          top: 1px;
          list-style: none;
          display: inline-block;
          padding-right: 15px;

          &:before {
            counter-increment: number;
            content: counter(number) + '、';
          }

          &:last-of-type {
            padding-right: 0;
          }
        }
      }
    }
  }

  .ant-table-cell {
    > ul {
      list-style: none;
      margin: 0;
      padding: 0;

      > li {
        font-size: 16px;
        font-weight: bold;

        > ul {
          list-style: none;
          margin: 0;
          padding: 0;
          margin-left: 15px;

          > li {
            font-size: 14px;
            font-weight: normal;
          }
        }
      }
    }
  }
</style>
